<?php
//thumbnail program
//Show that a jpeg image is going to be returned
//echo $QUERY_STRING;
//exit;
header("Content-type: image/jpeg");
//optionally add watermark; set to "1" if you want it.
$watermark = "0";


//File names
$wmark='watermark.png';
$mimage=str_replace(".thumb",".jpg",$QUERY_STRING);

// max thumbnail dimensions
$MAX_WIDTH=173;
$MAX_HEIGHT=173;


//Loading
if ($watermark == "1") { 
	$watermark_img = imagecreatefrompng($wmark); 
	imagecolortransparent($watermark_img,0);

	$wmrk_size = getimagesize($wmark);
}
$main_img = imagecreatefromjpeg($mimage);

if ($watermark == "1") { 

//Merge the 2 buffers
	imagecopymerge($main_img,$watermark_img,0,0,0,0,
               $wmrk_size[0],$wmrk_size[1],100); 
//or
//imagecopy($main_img,$watermark_img,0,0,0,0,
//            $wmrk_size[0],$wmrk_size[1]);
}

# Get image size and scale ratio
   $width = imagesx($main_img);
   $height = imagesy($main_img);
   $scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height);

   # If the image is larger than the max shrink it
   if ($scale < 1) {
       $new_width = floor($scale*$width);
       $new_height = floor($scale*$height);

       # Create a new temporary image
       $tmp_img = imagecreatetruecolor($new_width, $new_height);

       # Copy and resize old image into new image
       imagecopyresized($tmp_img, $main_img, 0, 0, 0, 0,
                        $new_width, $new_height, $width, $height);
       imagedestroy($main_img);
       $main_img = $tmp_img;
   }



//Output file to browser
imagejpeg($main_img);//(6)
if ($watermark == "1") { 
	imagedestroy($watermark_img);//(7)
}
imagedestroy($main_img);
?>
